﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IPC.Communication.Framework.BasicFramework;

namespace IPC.Communication.Framework.Core
{
    public class ReverseWordTransform : ByteTransformBase
    {
        public ReverseWordTransform()
        {
            base.DataFormat = DataFormat.ABCD;
        }

        public ReverseWordTransform(DataFormat dataFormat)
            : base(dataFormat)
        {
        }

        private byte[] ReverseBytesByWord(byte[] buffer, int index, int length)
        {
            if (buffer == null)
            {
                return null;
            }
            return SoftBasic.BytesReverseByWord(buffer.SelectMiddle(index, length));
        }

        public override short TransInt16(byte[] buffer, int index)
        {
            return base.TransInt16(ReverseBytesByWord(buffer, index, 2), 0);
        }

        public override ushort TransUInt16(byte[] buffer, int index)
        {
            return base.TransUInt16(ReverseBytesByWord(buffer, index, 2), 0);
        }

        public override byte[] TransByte(short[] values)
        {
            byte[] inBytes = base.TransByte(values);
            return SoftBasic.BytesReverseByWord(inBytes);
        }

        public override byte[] TransByte(ushort[] values)
        {
            byte[] inBytes = base.TransByte(values);
            return SoftBasic.BytesReverseByWord(inBytes);
        }

        public override IByteTransform CreateByDateFormat(DataFormat dataFormat)
        {
            return new ReverseWordTransform(dataFormat)
            {
                IsStringReverseByteWord = base.IsStringReverseByteWord
            };
        }

        public override string ToString()
        {
            return String.Format("ReverseWordTransform[{0}]", base.DataFormat);
        }
    }
}
